package jp.sourceforge.akjrcp.ui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Scale;
import org.eclipse.swt.widgets.Spinner;

public class SpinnerAndScale extends Composite implements SelectionListener{

	Spinner spinner;
	Scale scale;
	
	List selectionLisners=new ArrayList();
	public SpinnerAndScale(Composite parent, int style) {
		super(parent, style);
		this.setLayout(new GridLayout(2,false));
		spinner=new Spinner(this,SWT.READ_ONLY);//it's better if you prefer digit.
		scale=new Scale(this,SWT.NULL);
		scale.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
	
		spinner.addSelectionListener(this);
		scale.addSelectionListener(this);
	}
	public void setMaximum(int max){
		spinner.setMaximum(max);
		scale.setMaximum(max);
	}
	public void setMinimum(int min){
		spinner.setMinimum(min);
		scale.setMinimum(min);
	}
	public void setDigits(int digit){
		spinner.setDigits(digit);
	}
	public void setSelection(int selection){
		spinner.setSelection(selection);
		scale.setSelection(selection);
	}
	
	public int getSelection(){
		return spinner.getSelection();
	}
	public double getDigitedSelection(){

		int base=1;
		for(int i=0;i<spinner.getDigits();i++){
			base*=10;
		}
		return (double)getSelection()/base;
	}
	public void widgetDefaultSelected(SelectionEvent e) {
		// TODO Auto-generated method stub
		
	}
	public void widgetSelected(SelectionEvent e) {
		if(e.getSource()==scale){
			spinner.setSelection(scale.getSelection());
		}
		if(e.getSource()==spinner){
			scale.setSelection(spinner.getSelection());
		}
		//BUG?
		//e.widget=this;
		Iterator iter=selectionLisners.iterator();
		while(iter.hasNext()){
			SelectionListener selectionListener=(SelectionListener) iter.next();
			selectionListener.widgetSelected(e);
		}
	}
	
	public void addSelectionListener(SelectionListener selectionListener){
		selectionLisners.add(selectionListener);
	}
	public Scale getScale() {
		return scale;
	}
	public void setScale(Scale scale) {
		this.scale = scale;
	}
	public Spinner getSpinner() {
		return spinner;
	}
	public void setSpinner(Spinner spinner) {
		this.spinner = spinner;
	}

}
